<template>
  <view class="smart-form">
    <uni-forms :label-width="100" ref="formRef" :modelValue="formData" label-position="left" :rules="rules">
      <view class="smart-form-group smart-filed">
        <view class="smart-form-group-title smart-margin-top20"> 客户信息</view>
        <view class="smart-form-group-content">
          <uni-forms-item class="smart-form-item smart-margin-top20" label="姓名" name="customer" required>
            <uni-easyinput trim="all" v-model="formData.customer" placeholder="请输入姓名"/>
          </uni-forms-item>
          <uni-forms-item class="smart-form-item" label="身份证号" name="idNo" required>
            <uni-easyinput trim="all" v-model="formData.idNo" placeholder="请输入身份证号"/>
          </uni-forms-item>
          <uni-forms-item class="smart-form-item" label="车牌号码" name="vehicleNo" required>
            <uni-easyinput trim="all" v-model="formData.vehicleNo" placeholder="请输入车牌号码"/>
          </uni-forms-item>
          <uni-forms-item class="smart-form-item" label="手机号码" name="mobileNo" required>
            <uni-easyinput trim="all" v-model="formData.mobileNo" placeholder="请输入手机号码"/>
          </uni-forms-item>
        </view>
      </view>
      <view class="smart-form-group smart-filed">
        <view class="smart-form-group-title smart-margin-top20"> 收件信息</view>
        <view class="smart-form-group-content">
          <uni-forms-item class="smart-form-item" label="领取方式" name="receiptMethod" required>
            <SmartEnumSelect enumName="RECEIPT_METHOD_ENUM"  v-model="formData.receiptMethod" />
          </uni-forms-item>
          <uni-forms-item class="smart-form-item" label="收件人姓名" name="consignee"  required>
            <uni-easyinput trim="all" v-model="formData.consignee" placeholder="请输入收件人姓名"/>
          </uni-forms-item>
          <uni-forms-item class="smart-form-item" label="收件人电话" name="consigneeMobileNo" required>
            <uni-easyinput trim="all" v-model="formData.consigneeMobileNo" placeholder="请输入收件人电话"/>
          </uni-forms-item>
          <uni-forms-item class="smart-form-item" label="收件地址（省）" name="consigneeAddressProvince" required>
            <uni-data-select :localdata="provinceOptions" v-model="formData.consigneeAddressProvince"
                             placeholder="请选择省份" @change="selectProvince" :clear="false"/>
          </uni-forms-item>
          <uni-forms-item class="smart-form-item" label="收件地址（市）" name="consigneeAddressCity" required>
            <uni-data-select :localdata="cityOptions" v-model="formData.consigneeAddressCity"
                             placeholder="请选择城市" :disabled="formData.consigneeAddressProvince === undefined" @change="selectCity"
                             :clear="false"/>
          </uni-forms-item>
          <uni-forms-item class="smart-form-item" label="收件地址（区/县）" name="consigneeAddressDistrict" required>
            <uni-data-select :localdata="districtOptions" v-model="formData.consigneeAddressDistrict"
                             placeholder="请选择区/县" :disabled="formData.consigneeAddressCity === undefined"
                             :clear="false"/>
          </uni-forms-item>
          <uni-forms-item class="smart-form-item" label="详细地址" name="consigneeDetailAddress" required>
            <uni-easyinput trim="all" v-model="formData.consigneeDetailAddress" placeholder="请输入详细地址"/>
          </uni-forms-item>
          <uni-forms-item class="smart-form-item" label="邮政编码" name="postCode" required>
            <uni-easyinput trim="all" v-model="formData.postCode" placeholder="请输入邮政编码"/>
          </uni-forms-item>
        </view>
      </view>
      <view class="smart-form-group smart-filed">
        <view class="smart-form-group-title smart-margin-top20"> 费用支付</view>
        <view class="smart-form-group-content">
          <p>识别下方二维码完成支付，支付成功后保留截图，并在下方上传。</p>
          <br/>
          <image src="@/static/images/pay-record/pay.png"/>
          <p>识别上方二维码完成费用支付，付款完成后上传截图（支持 png、jpeg、pdf、jpg等格式）</p><br/>
          <uni-forms-item class="smart-form-item" label="上传支付凭证" name="otherIncomeProof">
            <uni-file-picker
                limit="1"
                @select='selectUploadByPaymentProof'
                :auto-upload='false'
                file-extname='png,git,jpeg,pdf,jpg'
                file-mediatype="image"
                v-model='formData.paymentFileKey'/>
          </uni-forms-item>
        </view>
      </view>
      <view class="smart-form-group smart-filed">
        <view class="smart-form-group-title smart-margin-top20"> 解除抵押常识</view>
        <view class="smart-form-group-content">
          <text class="content">
            当您收到登记证后，您需要完成以下几项事宜完成解除抵押：
          </text>
          <view class="list">
            <text class="item">1. 登记证原件<br/></text>
            <text class="item">2. 结清证明<br/></text>
            <text class="item">3. 金融公司营业执照<br/></text>
            <text class="item">4. 金融公司委托书<br/></text>
            <text class="item">5. 身份证原件<br/></text>
          </view>
          <text class="content"><br/>
            携带以上资料前往当地车管部门办理车辆解除抵押业务。完成解除抵押后方可正常出售/过户车辆。
          </text>
          <text class="content"><br/><br/>
            祝您用车愉快，如有其他车辆分期需求，也可联系客服在线沟通（联系电话：028-89760089，19008012770）！
          </text>
        </view>
      </view>
      <view class="smart-form-group smart-filed">
        <view class="smart-form-group-title smart-margin-top20"> 服务声明</view>
        <view class="smart-form-group-content">
          <p>本公司作为金融机构服务商，为给您提供更好更安全的服务，我司将在你确认后收取相应服务费用，如有疑问，请联系客服（028-89760089，19008012770）。</p>
          <uni-forms-item class="smart-form-item" label="我已知晓" name="confirmStatus" required>
            <checkbox-group @change="checkboxChange" class="agreement_radio">
              <checkbox :value="1" :checked="checked" />
            </checkbox-group>
          </uni-forms-item>
        </view>
      </view>
    </uni-forms>
    <view class="smart-form-submit fixed-bottom-button">
      <button class="smart-form-submit-btn" type="primary" @click="ok">提交</button>
    </view>
  </view>
</template>

<script setup>
import {reactive, ref} from 'vue';
import SmartEnumSelect from '@/components/smart-enum-select/index.vue';
import {vehicleLoanOrderApi} from '@/api/business/qr/vehicle-loan-order-api';
import {payRecordApi} from '@/api/business/qr/pay-record-api';
import {SmartLoading, SmartToast} from "../../lib/smart-support";
import {smartSentry} from "../../lib/smart-sentry";
import {fileApi} from "/@/api/support/file-api";
import {FILE_FOLDER_TYPE_ENUM} from "../../constants/support/file-const";
import {onShow} from "@dcloudio/uni-app";


// 组件ref
const formRef = ref();

const provinceOptions = ref([]);
const cityOptions = ref([]);
const districtOptions = ref([]);
const checked = ref(false);

onShow(queryProvinceZone);

function checkboxChange(e){
  if(e.detail.value[0] == 1){
    checked.value = true
    formData.confirmStatus = 1;
  }else{
    checked.value = false
    formData.confirmStatus = 0;
  }
}

async function selectUploadByPaymentProof(option) {
  const tempFilePaths = option.tempFilePaths;
  let res = await fileApi.upload(tempFilePaths[0], FILE_FOLDER_TYPE_ENUM.PAYMENT_PROOF.value);
  let file = res.data;
  file.url = file.fileUrl;
  file.name = file.fileName;
  formData.paymentFileKey.push(file);
}

async function queryProvinceZone() {
    // 延迟2秒
    await new Promise(resolve => setTimeout(resolve, 2000));
    let res = await vehicleLoanOrderApi.listByParentZoneId(100000);
    provinceOptions.value = res.data.map(item => ({ text: item.zoneName, value: item.zoneId }));
}


async function selectProvince() {
  let res = await vehicleLoanOrderApi.listByParentZoneId(formData.consigneeAddressProvince);
  cityOptions.value = res.data.map(item => ({text: item.zoneName, value: item.zoneId}));
  formData.consigneeAddressCity = undefined;
}

async function selectCity() {
  let res = await vehicleLoanOrderApi.listByParentZoneId(formData.consigneeAddressCity);
  districtOptions.value = res.data.map(item => ({text: item.zoneName, value: item.zoneId}));
  formData.consigneeAddressDistrict = undefined;
}

const formDefault = {
  payRecordId: undefined, //产证支付ID
  customer: undefined, //客户
  idNo: undefined, //证件号码
  vehicleNo: undefined, //车牌号
  mobileNo: undefined, //联系方式
  receiptMethod: undefined, //领取方式
  consignee: undefined, //收件人
  consigneeMobileNo: undefined, //收件人电话
  consigneeAddressProvince: undefined, //收件地址省份
  consigneeAddressCity: undefined, //收件地址城市
  consigneeAddressDistrict: undefined, //收件地址区/县
  consigneeDetailAddress: undefined, //收件详细地址
  postCode: undefined, //邮政编码
  paymentFileKey: [], //付款方式凭据
  confirmStatus: 0, //确认知晓
};

let formData = reactive({...formDefault});

const rules = {
  customer: {rules: [{required: true, errorMessage: '客户 必填'}]},
  idNo: {rules: [{required: true, errorMessage: '证件号码 必填'}]},
  vehicleNo: {rules: [{required: true, errorMessage: '车牌号 必填'}]},
  mobileNo: {rules: [{required: true, errorMessage: '联系方式 必填'}]},
  receiptMethod: {rules: [{required: true, errorMessage: '领取方式 必填'}]},
  consignee:{rules:  [{required: true, errorMessage: '收件人 必填'}]},
  consigneeMobileNo: {rules: [{required: true, errorMessage: '收件人电话 必填'}]},
  consigneeAddressProvince: {rules: [{required: true, errorMessage: '收件地址省份 必填'}]},
  consigneeAddressCity: {rules: [{required: true, errorMessage: '收件地址城市 必填'}]},
  consigneeAddressDistrict: {rules: [{required: true, errorMessage: '收件地址区/县 必填'}]},
  consigneeDetailAddress:{rules:  [{required: true, errorMessage: '收件详细地址 必填'}]},
  postCode: {rules: [{required: true, errorMessage: '邮政编码必填'}]},
  paymentFileKey:{rules:  [{required: true, errorMessage: '请上传付款方式凭据', trigger: 'change'}]},
  confirmStatus: {rules: [{required: true, errorMessage: '请勾选客户已经知晓', trigger: 'change'}]},
};

// 确定
function ok() {
  formRef.value
      .validate()
      .then(async () => {
        SmartLoading.show();
        try {
          if(formData.paymentFileKey.length === 0) {
            SmartToast.toast("请上传支付凭证")
          } else{
            console.log(formData)
            if (formData.confirmStatus == 1) {
              await payRecordApi.add(formData);
              SmartToast.success('添加成功');
            } else {
              SmartToast.toast("请勾选我已知晓")
            }
          }
        } catch (error) {
          smartSentry.captureError(error);
        } finally {
          SmartLoading.hide();
        }
      })
      .catch((error) => {
        console.log('error', error);
        SmartToast.toast('参数验证错误，请仔细填写表单数据!');
      });
}
</script>

<style lang="scss" scoped>
.smart-filed {
  :deep(.uni-forms-item) {
    margin-bottom: 0 !important;
  }
}
image {
  margin-left: 30rpx;
  width: 600rpx;
  height: 800rpx;
}
</style>
